package com.thirtywords.cleaner;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;

import com.thirtywords.analizer.Analyzer;
import com.thirtywords.analizer.beans.Link;

public class FrontCleaner extends CleanerRunnable {

	public FrontCleaner(String url, int deep) {
		super(url, deep);
	}

	@Override
	public void run() {

		if (code.getUrl() != null) {

			HashSet<String> invalidElements = new HashSet<String>();
			invalidElements.add(HTMLElementName.ACRONYM);
			invalidElements.add(HTMLElementName.SUB);
			invalidElements.add(HTMLElementName.SUP);
			invalidElements.add(HTMLElementName.IMG);
			invalidElements.add(HTMLElementName.TITLE);
			invalidElements.add(HTMLElementName.FORM);
			invalidElements.add(HTMLElementName.SCRIPT);
			invalidElements.add(HTMLElementName.ASIDE);

			try {
				System.out.println(">>" + code.getUrl());

				List<Link> links = new ArrayList<Link>();

				String line = "";
				StringBuilder builder = new StringBuilder();
				List<Element> elements = getElements(code);

				for (Element element : elements) {

					if (!invalidElements.contains(element.getName())
							&& element.getName().equals(HTMLElementName.A)) {

						Link link = new Link();
						link.setHref(element.getAttributeValue("href"));
						link.setText(element.getContent().getTextExtractor()
								.toString().trim());

						links.add(link);

						line = "<a href=" + link.getHref() + ">"
								+ link.getText() + "</a>";
						builder.append(line);
					}
				}

				System.out.println(">>>>" + builder.toString());

				code.setParsedCode(builder.toString());
				code.setDownloaded(new Date());
				Analyzer.cache.put(code.getUrl(), code);

				if (this.deep < FrontCleaner.MAX_DEEP) {
					getNextLevel(links);
				}

			} catch (Exception e) {
				//e.printStackTrace();
			}
		}
	}

	@Override
	public String doClean() {
		// TODO Auto-generated method stub
		return null;
	}
}
